/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boxin.ims.modules.momarketing.dao.QRCodeDao;
import com.boxin.ims.modules.momarketing.entity.QRCode;
import com.boxin.ims.modules.recharge.entity.Recharge;
import com.boxin.ims.modules.recharge.service.RechargeService;
import com.boxin.ims.modules.wechat.dao.WechatMemberDao;
import com.boxin.ims.modules.wechat.entity.LangType;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.utils.AssertUtils;
import com.boxin.ims.modules.wechat.utils.WechatInterfaceUtils;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.modules.sys.entity.User;

/**
 * 微信会员Service
 * @author Jakemanse
 * @version 2013-09-08
 */
@Component
@Transactional(readOnly = true)
public class WechatMemberService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(WechatMemberService.class);
	
	@Autowired
	private WechatMemberDao wechatMemberDao;
	
	@Autowired
	private QRCodeDao qrCodeDao;
	
	
	@Autowired
	private RechargeService rechargeService;
	
	
	public WechatMember get(Long id) {
		return wechatMemberDao.findOne(id);
	}
	

	/**
	 * @author Jakemanse
	 * @time 2014-5-7  上午11:54:21
	 * @function <p> 根据会员卡号得到会员 </p>
	 * @param number
	 * @return
	 */
	public WechatMember getByNumber(String number){
		return wechatMemberDao.getByNumber(number);
		
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-5-7  上午11:54:47
	 * @function <p>根据推荐码、暗号 查找 </p>
	 * @param number
	 * @return
	 */
	
	public WechatMember getByRecommandCode(String code){
		return wechatMemberDao.getByRecommandCode(code);
		
	}
	
	
	public WechatMember getBySceneId(String sceneId){
		return wechatMemberDao.getBySceneId(sceneId);
		
	}
	
	public WechatMember getByJiuSceneId(String sceneId){
		return wechatMemberDao.getByJiuSceneId(sceneId);
		
	}
	
	public WechatMember getByFinanceSceneId(String financeSceneId){
		return wechatMemberDao.getByFinanceSceneId(financeSceneId);
		
	}
	
	public WechatMember getByWechatId(String wechatId){
		return wechatMemberDao.getByWechatId(wechatId);
		
	}
	
	
	public int modifyName(String name,Long id){
		return wechatMemberDao.modifyName(name, id);
		
	}
	
	public int modifyMobile(String mobile,Long id){
		return wechatMemberDao.modifyMobile(mobile, id);
		
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-8  下午11:15:53
	 * @function <p> 根据微信 OpenId 得到 微信会员信息 </p>
	 * @param user
	 * @param wechatId
	 * @return
	 */
	public WechatMember getByWechatMemberId(User user,String wechatId){
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		dc.add(Restrictions.eq("user.id", user.getId()));
		dc.add(Restrictions.eq("wechatId", wechatId));
		
		List<WechatMember> members = wechatMemberDao.find(dc);
		if(members!=null && members.size()>0){
			return members.get(0);
		}
		return null;
	}
	
	public WechatMember getByWechatMemberId(Long userId,String wechatId){
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		dc.add(Restrictions.eq("user.id", userId));
		dc.add(Restrictions.eq("wechatId", wechatId));
		
		List<WechatMember> members = wechatMemberDao.find(dc);
		if(members!=null && members.size()>0){
			return members.get(0);
		}
		return null;
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-5  上午10:52:11
	 * @function <p> 根据会员卡 号获取会员对象 </p>
	 * @param userId
	 * @param number
	 * @return
	 */
	public WechatMember getByUserIdAndNumber(Long userId,String number){
		return wechatMemberDao.getByUserIdAndNumber(userId,number);
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-24  下午3:55:14
	 * @function <p>根据 </p>
	 * @param memberId
	 * @return
	 */
	public QRCode  getMemberQRCodeBy(WechatMember member){
		Recharge recharge = 	rechargeService.getRechargeByMemberId(member.getId());
		
		return (recharge == null)? null : recharge.getQrCode();
	}
	
	
	
	
	public WechatMember getByMobile(User user,String mobile){
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		dc.add(Restrictions.eq("user.id", user.getId()));
		dc.add(Restrictions.eq("mobile", mobile));
		List<WechatMember> members = wechatMemberDao.find(dc);
		if(members!=null && members.size()>0){
			return members.get(0);
		}
		return null;
	}
	
	public List<WechatMember> getMembersByMobile(User user,String mobile){
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		dc.add(Restrictions.eq("user.id", user.getId()));
		dc.add(Restrictions.eq("mobile", mobile));
		List<WechatMember> members = wechatMemberDao.find(dc);
		return members;
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-30  上午10:10:58
	 * @function <p> 查询我推荐的会员 </p>
	 * @param recomandCode
	 * @return
	 */
	public List<WechatMember> findMyRecommandMembers(String recomandCode){
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		dc.add(Restrictions.eq("parentCode", recomandCode));
		List<WechatMember> members = wechatMemberDao.find(dc);
		return members; 
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-23  上午11:25:57
	 * @function <p> 根据微信 绑写的手机号 得到 微信会员信息 </p>
	 * @param user
	 * @param wechatId
	 * @return
	 */
	public WechatMember getByWechatMobile(User user,String mobile){
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		dc.add(Restrictions.eq("user.id", user.getId()));
		dc.add(Restrictions.eq("mobile", mobile));
		List<WechatMember> members = wechatMemberDao.find(dc);
		if(members!=null && members.size()>0){
			return members.get(0);
		}
		return null;
	}
	
	public Page<WechatMember> find(Page<WechatMember> page, WechatMember wechatMember) {
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		dc.createAlias("user", "user");
		
		if (wechatMember.getUser()!=null &&wechatMember.getUser().getId()!=null &&wechatMember.getUser().getId()>0){
			dc.add(Restrictions.eq("user.id", wechatMember.getUser().getId()));
		}
		
		if (wechatMember.getUser()!=null && StringUtils.isNotEmpty(wechatMember.getUser().getName())){
			dc.add(Restrictions.like("user.name", "%"+wechatMember.getUser().getName()+"%"));
		}
		
		
		if (StringUtils.isNotEmpty(wechatMember.getName())){
			dc.add(Restrictions.like("name", "%"+wechatMember.getName()+"%"));
		}
		
		if(wechatMember.getCreateTime() !=null){
			String timeField = "createTime";
			dc.add(Restrictions.ge(timeField,wechatMember.getCreateTime() ));
		}
		
		//大于等的分数
		if (wechatMember.getScore()!=null ){
			dc.add(Restrictions.ge("score", wechatMember.getScore()));
		}		
		
		if (wechatMember.getActiveScore()!=null ){
			dc.add(Restrictions.ge("activeScore", wechatMember.getActiveScore()));
		}	
		if (wechatMember.getConsumeScore()!=null ){
			dc.add(Restrictions.ge("consumeScore", wechatMember.getActiveScore()));
		}	
		if (wechatMember.getCreditScore()!=null ){
			dc.add(Restrictions.ge("score", wechatMember.getCreditScore()));
		}
		if (wechatMember.getUnusable()!=null ){
			dc.add(Restrictions.ge("unusable", wechatMember.getUnusable()));
		}
		if(wechatMember.getEndTime() !=null){
			String timeField = "createTime";
			dc.add(Restrictions.le(timeField,wechatMember.getEndTime()));
		}
		
		if (StringUtils.isNotEmpty(wechatMember.getMobile())){
			dc.add(Restrictions.like("mobile", "%"+wechatMember.getMobile()+"%"));
		}
		if (StringUtils.isNotEmpty(wechatMember.getRemarks())){
			dc.add(Restrictions.like("remarks", "%"+wechatMember.getRemarks()+"%"));
		}
		if (StringUtils.isNotEmpty(wechatMember.getZhuce())){
			dc.add(Restrictions.isNotNull("mobile"));
		}
		if (wechatMember.getId()!=null){
			dc.add(Restrictions.eq("id",wechatMember.getId()));
		}
		dc.add(Restrictions.eq("delFlag", WechatMember.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		return wechatMemberDao.find(page, dc);
	}
	
	
	public Page<WechatMember> findMember(Page<WechatMember> page, WechatMember wechatMember) {
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		/*dc.createAlias("user", "user");
		
		if (wechatMember.getUser()!=null &&wechatMember.getUser().getId()!=null &&wechatMember.getUser().getId()>0){
			dc.add(Restrictions.eq("user.id", wechatMember.getUser().getId()));
		}*/
		
		if (StringUtils.isNotEmpty(wechatMember.getName())){
			dc.add(Restrictions.or(Restrictions.like("name", "%"+wechatMember.getName()+"%"),Restrictions.like("nickname", "%"+wechatMember.getName()+"%")));
		}
		
		dc.add(Restrictions.eq("delFlag", WechatMember.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		return wechatMemberDao.find(page, dc);
	}
	
	public List<WechatMember> find(WechatMember wechatMember) {
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		
		if (StringUtils.isNotEmpty(wechatMember.getIsAdmin())){
			dc.add(Restrictions.eq("isAdmin",wechatMember.getIsAdmin()));
		}
		dc.add(Restrictions.eq("delFlag", WechatMember.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		return wechatMemberDao.find(dc);
	}
	
	@Transactional(readOnly = false)
	public void save(WechatMember wechatMember) {
		
		
		wechatMemberDao.save(wechatMember);
	}
	
	
	@Transactional(readOnly = false)
	public void delete(Long id) {
		wechatMemberDao.deleteById(id);
	}
	
	@Transactional(readOnly = false)
	public void remove(Long id) {
		wechatMemberDao.removeById(id);
	}
	
	@Transactional(readOnly = false)
	public void deleteByUserIdAndWechatId(Long userId,String wid) {
		wechatMemberDao.deleteByUserIdAndWechatId(userId,wid);
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-10  下午11:04:19
	 * @function <p> 查用户下所有的会员 </p>
	 * @param userId
	 * @return
	 */
	public List<WechatMember> findAllMembersByUserId(Long userId){
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		dc.add(Restrictions.eq("user.id",userId));
		List<WechatMember> members=wechatMemberDao.find(dc);
		return members;
	}
	
	
	
	
	
	@Transactional(readOnly = false)
	public void updateWechatMemberFromWechat(String accessToken,WeChat weChat) throws Exception{
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		dc.add(Restrictions.eq("user.id",weChat.getUser().getId()));
		List<WechatMember> members=wechatMemberDao.find(dc);
		for (WechatMember wechatMember : members) {
			
			WechatMember temp=WechatInterfaceUtils.getUserMessage(accessToken, wechatMember.getWechatId(), LangType.zh_CN);
			wechatMember.setNickname(temp.getNickname());
			wechatMember.setAge(temp.getAge());
			wechatMember.setProvince(temp.getProvince());
			wechatMember.setCity(temp.getCity());
			wechatMember.setCountry(temp.getCountry());
			wechatMember.setLanguage(temp.getLanguage());
			wechatMember.setHeadimgurl(temp.getHeadimgurl());
			wechatMember.setSubscribeTime(temp.getSubscribeTime());
			logger.debug("正在同步"+wechatMember.getName()+"的高级接口信息...");
			wechatMemberDao.save(wechatMember);
		}
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-31  下午11:52:31
	 * @function <p>更新 生成会员 卡号  </p>
	 * @param member
	 * @throws Exception
	 */
	@Transactional(readOnly = false)
	public void updateWechatMemberCardNumber(WechatMember member) throws Exception{
		//wechatMemberDao.updateWechatMemberCardNumber(member.getId());
	}
	
	
	
	
	/**
	 * 查看我的推荐会员
	 */
	public List<WechatMember> selectMyCommend(String recommendCode,List<Map<String, Object>> list) {
		List<WechatMember> mycomendList = new ArrayList<WechatMember>(); // 我的推荐会员list
		List<WechatMember> soncomendList = new ArrayList<WechatMember>(); // 推荐会员的推荐会员list
		List<WechatMember> myList = new ArrayList<WechatMember>(); // 临时list
		WechatMember wechatMember = new WechatMember();
		WechatMember sonwechatMember = new WechatMember();
		
		if (AssertUtils.notNull(list)) {
			if (list.size()<1) {
				list = null;
			}
			else {
				myList = this.mapListToMemberList(list);// 我推荐的会员

				for (int i = 0; i < myList.size(); i++) {
					wechatMember = myList.get(i);
					
					if (wechatMember.getParentCode().equals(recommendCode)) {
						mycomendList.add(wechatMember);
					}

				}//父推荐码等于推荐recommendCode
				
				for (int i = 0; i < mycomendList.size(); i++) {
					wechatMember = mycomendList.get(i);
					soncomendList = new ArrayList<WechatMember>();
					for (int j = 0; j < myList.size(); j++) {
						sonwechatMember = myList.get(j);
						if (wechatMember.getRecommendCode().equals(sonwechatMember.getParentCode())) {
							soncomendList.add(sonwechatMember);
							
						}
					}
					
					if (AssertUtils.notNull(soncomendList)) {
					
						if (soncomendList.size()>0) {
							wechatMember.setSonWechatMemberList(soncomendList);
						}
						else {
							wechatMember.setSonWechatMemberList(null);
						}
					}
					else {
						wechatMember.setSonWechatMemberList(null);
					}
					
					
				}
			}
		}

		

		return mycomendList;
	}

	/**
	 * 把List<Map<String, Object>> 对象 转为 List<WechatMember>
	 */
	public List<WechatMember> mapListToMemberList(
			List<Map<String, Object>> mapList) {

		List<WechatMember> myList = new ArrayList<WechatMember>();

		WechatMember wechatMember = new WechatMember();

		for (int i = 0; i < mapList.size(); i++) {
			wechatMember = new WechatMember();

			wechatMember.setId(Long.parseLong(mapList.get(i).get("id")
					.toString()));
			wechatMember.setName(mapList.get(i).get("name").toString());
			wechatMember.setRecommendCode(mapList.get(i).get("recommend_code")
					.toString());
			wechatMember.setParentCode(mapList.get(i).get("parent_code")
					.toString());

			myList.add(wechatMember);

		}

		return myList;
	}
	
	
	public void clear(){
		this.wechatMemberDao.clear();
	}
	
	
	public Long getMemberCount(Long userId){
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		if (userId!=null){
			dc.add(Restrictions.eq("user.id", userId));
		}
		return wechatMemberDao.count(dc);
	}

	
	public void updateMemberByIsAdmin(String isAdmin,Long memberId){
		this.wechatMemberDao.updateBySql("update wp_wechat_member set is_admin= "+isAdmin+" where id="+memberId, null);
	}
	
	
	
	/**
	 * 查询推荐人数
	 *@author xiaoqian
	 * @param recomandCode
	 * @return
	 * 2015-1-9下午12:41:46
	 */
	public Long findMyRecommandMembersCount(String recomandCode){
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		dc.add(Restrictions.eq("parentCode", recomandCode));
		return wechatMemberDao.count(dc); 
	}

	
	/**
	 * 获取  用户注册排位
	 *@author xiaoqian
	 * @param userId
	 * @param memberId
	 * @return
	 * 2015-1-9下午2:07:54
	 */
	public Long getMemberNum(Long userId,Long memberId){
		DetachedCriteria dc = wechatMemberDao.createDetachedCriteria();
		if (userId!=null){
			dc.add(Restrictions.eq("user.id", userId));
		}
		if (memberId!=null){
			dc.add(Restrictions.lt("id", memberId));
		}
		return wechatMemberDao.count(dc);
	}
	
	public WechatMember getMemberByRecommendCode(String recommendCode){
		WechatMember wechatMember = wechatMemberDao.getByRecommandCode(recommendCode);
		return wechatMember;
	}
	
	/**
	 * 修改推荐人
	 * @param parentCode
	 * @param memberId
	 */
	public void updateRecommendMemberById(String parentCode,Long memberId){
		this.wechatMemberDao.updateBySql("update wp_wechat_member set parent_code= '"+parentCode+"' where id="+memberId, null);
	}
	

	public WechatMember getByUserIdAndOpenId(Long userId,String openId){
		return wechatMemberDao.getByUserIdAndOpenId(userId,openId);
	}
	
	@Transactional(readOnly = false)
	public void addRecommendScoreById(Integer recommendScore,Long id) {
		wechatMemberDao.addRecommendScoreById(recommendScore,id);
	}

}
